import { calcFieldValue } from '/@/components/Linxyun/custom/CustomCommon/lxy_expression.js';
import { ElMessage } from 'element-plus';
// 页面中的按钮组件;
class Event_controller {
	// _event_list = [];
	_exec_type = 0; // 0: 执行到错误产生时，中断后面的事件; 1: 独立的，前面即使失败也继续执行后面的;

	// ifConfirm = false;
	// _confirm_title = "";
	// _confirm_content = "";

	// successIfClose = false;
	// failIfClose = false;
	// _parent_page_eventid = null;
	constructor(cfg, listEvents, vm, collectedUp = []) {
		this.eventList = listEvents;
		const {
			ifConfirm,
			ifUpload,
			confirmOpt,
			ifRefreshCurr,
			ifRefreshEmit,
			failIfClose,
			successIfClose,
			closeIfEmit,
			closeEmitAction,
			enableJump,
			jumpUrlAddress,
			params,
			FieldID,
		} = cfg;
		this.ifConfirm = ifConfirm; // 执行前是否需要确认
		if (ifConfirm) {
			this._confirm_title = confirmOpt.title || '';
			this._confirm_content = confirmOpt.message || '';
		}
		this.ifUpload = ifUpload || false; // 执行前是否收集数据

		this.successIfClose = successIfClose || false; // 执行成功后是否关闭当前页
		this.failIfClose = failIfClose || false; // 执行失败后是否关闭当前页
		this.ifRefreshCurr = ifRefreshCurr || false; // 执行成功是否刷新当前页
		this.ifRefreshEmit = ifRefreshEmit || false; // 执行成功是否刷新上级前页面
		this.closeIfEmit = closeIfEmit || false; // 关闭当前页执行上级函数
		this.enableJump = enableJump || false; // 跳转到指定页面
		this.closeEmitAction = closeEmitAction || false;
		if (this.enableJump) {
			this.jumpUrlAddress = jumpUrlAddress || false;
			this.params = params || [];
			this.FieldID = FieldID || null;
		}

		// 上传前的依赖
		this.collectedUp = collectedUp;
		// 向上级导出数据
		this.exportData = {
			flag: false,
			data: {},
		};
		this.vm = vm;
	}

	// page_define: 页面定义对象;
	// datas      : 页面的数据对象;
	async run(datas, rowIndex = -1) {
		// 按钮点击事件;
		console.log('[Debug][CtrlerEvents]Run events: ', this);
		const that = this.vm;
		let ret = true;
		if (this.ifConfirm) {
			that
				.$confirm(this._confirm_content, this._confirm_title)
				.then(async () => {
					ret = await this.handleEvents(datas, rowIndex);
					this.vm.clone();
				})
				.catch(() => {
					that.$message({
						type: 'info',
						message: '已取消操作1',
					});
				});
		} else if (this.enableJump) {
			const newData = {};

			// 处理参数
			for (let index = 0; index < this.params.length; index++) {
				const item = this.params[index];
				const value = calcFieldValue(4, item.value, datas._input_params, datas._params, datas._global_params);
				newData[item.name] = ![undefined, NaN, null, '', 'undefined'].includes(value) ? value : '';
			}

			// 保存参数
			if (this.vm && this.vm.pageid && this.FieldID && newData) {
				sessionStorage.setItem(this.vm.pageid + '_' + this.FieldID, JSON.stringify(newData));
			}
		} else {
			console.log('datasdatasdatas', datas);
			ret = await this.handleEvents(datas, rowIndex);
			if (this.successIfClose && !this.ifConfirm) {
				this.vm.clone();
			}
		}
		console.log('exportData', this.exportData);
		this.execAfter(ret);
	}
	async handleEvents(datas, rowIndex = -1) {
		console.log('handleEvents', this.collectedUp);
		if (this.ifUpload) {
			const cb = this.collectedUp.map(({ vm, cpn }) => {
				return vm.$refs[cpn.vModel][0].submit(vm.tempFormData[cpn.vModel]);
			});
			await Promise.all(cb);
		}

		const that = this.vm;
		const Page = that.pageInfo || that.state.pageInfo;
		let eventObj = null;
		let ret = true;
		console.log('handleEvents eventList', this.eventList, Page);
		for (const event of this.eventList) {
			eventObj = Page.getEvent(event);
			console.log('[Debug][CombinationEvent][Call]event: ', { ...eventObj });
			if (eventObj === null) {
				console.error('[Error][CombinationEvent][Call]The event is not exist, event: ', event);
				ret = false;
				continue;
			}
			// 是否向上级导出数据
			if (eventObj.cfg && eventObj.cfg.actionType === 4) {
				this.exportData.flag = true;
				console.log('是否向上级导出数据', this.exportData);
			}
			eventObj.setDataSrcMgr(datas);
			const resTmp = await eventObj.callEvent(null, rowIndex, that);
			console.log('[Debug][CombinationEvent][Call]11111 res: ', resTmp);
			if (resTmp === null || resTmp.code !== '0000') {
				ret = false;
			} else {
				if (resTmp.msg) {
					// ElMessage.success(resTmp.msg);
				}
			}
			// 向上级导出数据
			if (this.exportData.flag) {
				Reflect.deleteProperty(resTmp, 'code');
				this.exportData.data = resTmp;
			}
		}
		return ret;
	}

	execAfter(ret) {
		let isCloseCurrent = false;
		console.log('execAfter', this.exportData, ret);
		// 后置
		if (ret) {
			// 执行成功

			if (this.successIfClose && !this.ifConfirm) {
				this.vm.handleCloseDialog();
				this.vm.clone();
				isCloseCurrent = true;
			}
			if (this.ifRefreshCurr) {
				this.vm.handleRefreshCurr();
			}
			if (this.ifRefreshEmit) {
				this.vm.handleRefreshEmit();
			}
			if (this.exportData.flag) {
				this.vm.handleExportData(this.exportData.data);
			}
		} else {
			// 执行失败
			if (this.failIfClose) {
				this.vm.handleCloseDialog();
				isCloseCurrent = true;
			}
		}

		if (isCloseCurrent) {
			if (this.closeIfEmit) {
				this.vm.handleEmitEvent('sendEmitAction', this.closeEmitAction);
			}
		}

		if (this.enableJump && this.jumpUrlAddress) {
			let from = '';
			if (this.vm && this.vm.pageid && this.FieldID) {
				from = this.vm.pageid + '_' + this.FieldID;
			}
			this.vm.$router.push({ path: this.jumpUrlAddress, query: { from: from } });
		}
	}
}

export default Event_controller;
